<?php

/*
|--------------------------------------------------------------------------
| Application & Route Filters
|--------------------------------------------------------------------------
|
| Below you will find the "before" and "after" events for the application
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/

App::before(function($request)
{
	//
});


App::after(function($request, $response)
{
	//
});

/**
 * 粗略过滤所有借口的参数:Parameter 中定义的 正则,必须,枚举
 */
Route::filter('checkParameter', function() {
    $parameter = Parameter::getParameter();
    foreach($parameter[Request::path()] as $k => $v) {
        if($v['necessary'] == true && !Input::has($k)) {
            echo new ApiOutput('lack_parameter', array('parameter' => $k)); exit;
        }
        if(isset($v['regex']) && !preg_match($v['regex'], Input::get($k))) {
            echo new ApiOutput('regex_error', array('parameter' => $k)); exit;
        }
        if(isset($v['enum']) && !in_array(Input::get($k), $v['enum'])) {
            echo new ApiOutput('enum_error', array('parameter' => $k)); exit;
        }
    }
});

//检查昵称是否存在
Route::filter('isNicknameExist', function() {
    $nickname = Request::get('nickname');
    $user = DB::table('user')->where('nickname', $nickname)->first();
    if(!is_null($user) && 'api/user/register' == Request::path()) {
        echo new ApiOutput('nickname_exist', array('parameter' => 'nickname')); exit;
    }
});

//检查手机号码是否存在
Route::filter('isPhoneExist', function() {
    $phone = Request::get('phone');
    $user = DB::table('user')->where('phone', $phone)->first();
    if(!is_null($user) && 'api/user/register' == Request::path()) {
        echo new ApiOutput('phone_exist', array('parameter' => 'phone')); exit;
    }
});

//检查邮箱是否存在
Route::filter('isEmailExist', function() {
    $email = Request::get('email');
    $user = DB::table('user')->where('email', $email)->first();
    if(!is_null($user) && 'api/user/register' == Request::path()) {
        echo new ApiOutput('email_exist', array('parameter' => 'email')); exit;
    }
});


